import tools from '@/utils/tools'
import moment from 'moment'
import fetchService from '@/service/loginService'
import uuidv1 from 'uuid/v1'
let OSS = require('ali-oss')
const VUE_APP_ALIYUN_OSS_REGION = 'oss-cn-chengdu'
const VUE_APP_ALIYUN_OSS_ACCESS_KEY_ID = 'LTAI4GACR4j5GMBwzpdRUbk9'
const VUE_APP_ALIYUN_OSS_ACCESS_KEY_SECRET = 'iwTSP7Y0KJdUfop0dTt4o03SVTEVjH'
const VUE_APP_ALIYUN_OSS_BUCKET = 'gydj-oss'
const VUE_APP_ALIYUN_OSS_BUCKET_DOMAIN = 'https://gydj-oss.oss-cn-chengdu.aliyuncs.com/'
let client = new OSS({
  region: VUE_APP_ALIYUN_OSS_REGION,
  accessKeyId: VUE_APP_ALIYUN_OSS_ACCESS_KEY_ID,
  accessKeySecret: VUE_APP_ALIYUN_OSS_ACCESS_KEY_SECRET,
  bucket: VUE_APP_ALIYUN_OSS_BUCKET
})

// 上传文件
export async function ossUpload (file, filePath) {
  let res = {}
  try {
    if (file.length > 0) {
      file = file[0]
    }
    // object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
    // yyyymm
    let ext = file.name.substr(file.name.lastIndexOf('.'))
    filePath = filePath || `APP/${tools.getUserInfo().id}/${moment().format('YYYYMM')}/${Date.now()}_${encodeURI(ext)}`
    let fileUrl = `${VUE_APP_ALIYUN_OSS_BUCKET_DOMAIN}${filePath}`
    const result = await client.multipartUpload(filePath, file)
    console.log('result====', result)
    res = result
    res.fileUrl = fileUrl
    // const head = await client.head(file.name)
    // console.log('requestUrls', result.res.requestUrls[0])
  } catch (e) {
    // 捕获超时异常。
    res.code = 201
    if (e.code === 'ConnectionTimeoutError') {
      console.log('TimeoutError')
      res.msg = '连接超时'
    }
    console.log(e)
  }
  console.log('上传返回结果:>>>', res)
  return res
}

// 文件添加到文件中心 fileSystem:OSS  VOD
// OSS https://laminae-oss.oss-cn-chengdu.aliyuncs.com/用户ID
async function addFileCenter (fileSystem = 'OSS', fileId, fileUrl, fileName) {
  let coverStatus = '1'
  let params = {
    fileSystem,
    fileId,
    coverStatus,
    fileName
  }
  if (fileSystem === 'OSS') {
    params.desc = fileUrl
  }
  const result = await new Promise((resolve, reject) => {
    fetchService.sysFileSave(params).then(res => {
      console.log('保存附件：', res)
      if (res.code === 0) {
        resolve(res.data)
      } else {
        reject({})
      }
    }).catch(e => {
      reject({})
    })
  })
  console.log(result)
  return result
}

export async function uploadOssAndFileCenter (file, filePath) {
  let uploadData = await ossUpload(file, filePath)
  let fileId = uuidv1().replace(/-/g, '')
  let addFileData = await addFileCenter('OSS', fileId, uploadData.fileUrl, file.name)
  addFileData.fileName = file.name
  addFileData.size = file.size
  return addFileData
}
